﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CalculatorFlexibe.Interfaces;

namespace CalculatorFlexibe
{
    class Calculator
    {
        private IOperation [] operationsArray;
        private INullPriorityOperation nullOperation;
        
        private IChanger changer;
        private IGetOperands getter;
        
        public Calculator(IChanger changer, 
                          IGetOperands getter,
                          INullPriorityOperation nullOperation,
                          //IOperation operation,
                          IUploader uploader)
        {
            operationsArray = uploader.UploadOperations(getter, changer);
            this.nullOperation = nullOperation;
            this.changer = changer;
            this.getter = getter;
        }

        public string Execute(string expr)
        {
            while (nullOperation.IsThereNesting(expr))
            {
                string str = nullOperation.GetExpressionWithoutNesting(expr);
                int leftBoundary = expr.IndexOf(str);
                int rightBoundary = leftBoundary + str.Length - 1;
                Array.ForEach(operationsArray, p => str = p.Execute(str));
                double result = Convert.ToDouble(str);
                expr = changer.ChangeOnResult(leftBoundary - nullOperation.leftBoundary.Length,
                                       rightBoundary + nullOperation.rightBoundary.Length,
                                       expr, 
                                       result);
            }
            Array.ForEach(operationsArray, p => expr = p.Execute(expr));
            return expr;
        }
    }
}
